<?php
/**
 * Here is your custom functions.
 */

use app\api\logic\WechatUserLogic;
use app\supplyDemand\logic\supplyDemandLogic;
use Tinywan\Jwt\JwtToken;
use support\think\Db;
if (!function_exists('getWechatInfo')) {
    /**
     * 获取当前登录用户
     */
    function getWechatInfo(): bool|array
    {
        if (!request()) {
            return false;
        }
        try {
            $token =JwtToken::getExtend();
            if ($token['scene'] != 'api') {
                throw new \Exception('非法场景 Token');
            }
        } catch (\Throwable $e) {
            return false;
        }
        return $token;
    }

    /**
     * 简化版腾讯地图地址转经纬度
     * @param string $address 地址
     * @param string $apiKey API密钥
     * @return array 经纬度数组(lng, lat)，失败则为null
     */
    function getLocation($address, $apiKey) {
        // 基础参数检查
        if(empty($address) || empty($apiKey)) return null;

        // 构建请求URL
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?".http_build_query([
                'address' => $address,
                'key' => $apiKey
            ]);

        // 初始化cURL
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            // 处理SSL问题（根据环境选择是否开启验证）
            CURLOPT_SSL_VERIFYPEER => false,  // 生产环境建议改为true并配置CA
            CURLOPT_SSL_VERIFYHOST => 0
        ]);

        // 执行请求
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        // 检查错误
        if($error) return null;
        return $response;
    }

    /**
     * 记录供需日志
     *
     * @param int $user_id 用户ID
     * @param array $product 商品信息数组，需包含'sd_id'和'product_name'字段
     * @param int $type 日志类型：1-浏览商品，2-收藏，3-对接，4-取消收藏
     * @return bool 操作是否成功
     */
    function supplyLog($user_id, $product, $type) {
        // 验证参数
        if (empty($user_id) || !is_array($product) || !isset($product['sd_id'], $product['product_name']) || !in_array($type, [1, 2, 3, 4])) {
            // 可以根据实际需求改为抛出异常或记录错误日志
            return false;
        }

        // 日志类型描述映射
        $typeDescriptions = [
            1 => '浏览商品',
            2 => '收藏此商品',
            3 => '对接此商品',
            4 => '取消收藏商品'
        ];

        // 实例化逻辑层
        $db = Db::table('eb_product_logs');

        // 查询是否已有该记录
        $condition = [
            'user_id' => $user_id,
            'product_id' => $product['sd_id'],
        ];
        if($type == 1 || $type == 3){
            $condition['type'] =$type;
            $existingLog = $db->where($condition)->find();
        }else{
            $existingLog = $db->where($condition)->whereIn('type',[2,4])->find();
        }


        // 计算次数（取消收藏不累计次数）
        $num = $existingLog ? intval($existingLog['num']) : 0;
        if($type == 1 || $type == 3) {
            $num++;
        }
        if($type == 2 ){
            $num = 1;
        }
        if($type == 4){
            $num = 0;
        }
        switch ($type){
            case 1:
            case 3:
            // 构建备注信息
            $remark = "第[{$num}]次{$typeDescriptions[$type]},商品名称:{$product['product_name']}";
                break;
            case 2:
            case 4:
            // 构建备注信息
            $remark = "{$typeDescriptions[$type]},商品名称:{$product['product_name']}";
                break;
        }


        // 准备数据
        $data = [
            'user_id' => $user_id,
            'product_id' => $product['sd_id'],
            'type' => $type,
            'remark' => $remark,
            'create_time' => date('Y-m-d H:i:s'), // 使用24小时制
            'num' => $num,
        ];

        // 执行数据库操作

        if ($existingLog) {
            $res = $db->where($condition)->update($data);
        } else {
            $res = $db->insert($data);
        }

        return (bool)$res;
    }

//    //计算商品权重
    function  productRole($user_id,$type,$page=0,$limit=0,$param=[]){
        //获取商品
     //  $user_id=65;

        $ebSupplyDemand=new supplyDemandLogic();
        if($type ==1){
            $supplyDemandData=$ebSupplyDemand
                ->field('sd_id,product_name,product_subtitle,image,supply_demand,enterprise_id,product_category')
                ->select()
                ->toArray();
        }else{
            // 初始化空的条件数组
            $where = [];

// 处理模糊搜索条件
            if (!empty($param['product_name'])) {
                $keyword = "%{$param['product_name']}%";
                $where[] = ['product_name', 'like', $keyword];
            }else{
                $where[] = ['product_category', '=', $param['product_category']];
            }

// 添加其他条件（统一使用二维数组格式）
            $where[] = ['lang_code', '=', $param['lang_code']];

            $where[] = ['supply_demand', '=', $param['supply_demand']];

// 执行查询
            $supplyDemandData = $ebSupplyDemand
                ->where($where)
                ->field('sd_id,product_name,product_subtitle,image,supply_demand,enterprise_id,product_category')
                ->select()
                ->toArray();
        }

        foreach ($supplyDemandData as $key => &$val){
            //获取用户设置的权重
            if(!empty($user_id)){
                $userLogic=new WechatUserLogic();
                $weight =$userLogic->where(['user_id'=>$user_id])->find();
             //   print_r($weight);
            }else{
                $weight=[];
            }
            if(!empty($user_id)) {
                $db = Db::table('eb_product_logs');
                //浏览次数
                $existingLog1 = $db->where(['user_id' => $user_id, 'product_id' => $val['sd_id'], 'type' => 1])->find();
                //收藏状态
                $existingLog2 = $db->where(['user_id' => $user_id, 'product_id' => $val['sd_id']])->whereIn('type', [2, 4])->count();
                //对接次数
                $existingLog3 = $db->where(['user_id' => $user_id, 'product_id' => $val['sd_id'], 'type' => 3])->find();
            }else{
                //浏览次数
                $existingLog1 = [];
                //收藏状态
                $existingLog2 =[];
                //对接次数
                $existingLog3 =[];
            }
            //根据规则计算商品权重  19 供应  20 需求
            $num1 =empty($existingLog1)?0:$existingLog1['num'];
            $num2 =empty($existingLog2)?0:$existingLog2['num'];
            $num3 =empty($existingLog3)?0:$existingLog3['num'];

            $supply_weight = empty($weight)?1:$weight['supply_weight'];
            $browsing_weight =empty($weight)?1:$weight['browsing_weight'];
            $collection_weight =empty($weight)?1:$weight['collection_weight'];
            $docking_eight =empty($weight)?1:$weight['docking_eight'];

            $number = $supply_weight*($browsing_weight*$num1+$collection_weight*$num2+$docking_eight*$num3);
            $val['number'] = $number;
        }
     //   print_r($supplyDemandData);
        //数组排序 根据 number
        // 提取需要排序的字段列
        $sort_number = array_column($supplyDemandData, 'number');

        // 根据price字段升序排序
        array_multisort($sort_number, SORT_DESC, $supplyDemandData);
        if($type == 1){  //首页获取
           $data =  array_slice($supplyDemandData, 0, 4);  // 获取排序后的前4条数据
        }else{ //列表也获取
            // 获取第2页，每页10条
            $data = arrayPagination($supplyDemandData, $page, $limit);
        }
        //返回数据
        return $data;


    }

    /**
     * 数组分页函数
     * @param array $array 要分页的数组
     * @param int $page 当前页码（从1开始）
     * @param int $pageSize 每页显示条数
     * @return array 分页后的结果，包含数据和分页信息
     */
    function arrayPagination($array, $page = 1, $pageSize = 10) {
        // 验证参数
        $page = max(1, (int)$page); // 确保页码为正整数
        $pageSize = max(1, (int)$pageSize); // 确保每页条数为正整数

        // 计算总条数
        $total = count($array);

        // 计算总页数
        $totalPages = ceil($total / $pageSize);

        // 确保页码不超过总页数
        $page = min($page, $totalPages);

        // 计算起始位置
        $offset = ($page - 1) * $pageSize;

        // 截取当前页数据
        $currentData = array_slice($array, $offset, $pageSize);

        // 返回分页结果
        return [
            'data' => $currentData,          // 当前页数据
            'pagination' => [
                'total' => $total,           // 总条数
                'page' => $page,             // 当前页码
                'pageSize' => $pageSize,     // 每页条数
                'totalPages' => $totalPages  // 总页数
            ]
        ];
    }


 }